package com.example.grape_effect.effet.filter

import com.example.grape_effect.gl.common.ShaderConstant


class CartoonFilter: LYFilter() {
    init {
        name = "cartoonFilter"
    }
    override var vertexShader = ShaderConstant.NO_FILTER_VERTEX_SHADER
    override var fragmentShader =  """
        precision highp float;
varying vec2 textureCoordinate;
uniform sampler2D inputTexture;
const float wStep = 5.0/750.0;
const float hStep = 5.0/770.0;
const float sRadio = 5.0;
void main()
 {

     vec4 color = texture2D( inputTexture, textureCoordinate);
     // 转 his颜色空间
     // Intensity分量[0, 1]
     float fIntensity = (color.r + color.g + color.b)/3.0;
     float min_rgb = min(color.r, color.g);
     min_rgb = min(min_rgb, color.b);


//     float fHue, fSaturation, fIntensity;
     float fSaturation = 1.0 - (3.0 * min_rgb) / (color.r + color.g + color.b);

     float numerator = (color.r - color.g + color.r - color.b) / 2.0;
     float denominator = sqrt((color.r - color.g)*(color.r - color.g) + (color.r - color.b)*(color.g - color.b));

//     // 计算Hue分量
     float fHue = 0.0;
     if (denominator != 0.0)
     {
         float theta = acos(numerator / denominator) * 180.0 / 3.14;

         if (color.b <= color.g)
         {
             fHue = theta;
         }
         else
         {
             fHue = 360.0 - theta;
         }
     }
     else
     {
         fHue = 0.0;
     }

     float H = fHue;
     float S = fSaturation * sRadio;
//     S = max(min(S , 1.0), 0.0);
     float I = fIntensity;

      float dTempB, dTempG, dTempR;//highp
     // RG扇区
     if (H < 120.0 && H >= 0.0)
     {
         // 将H转为弧度表示
         H = H * 3.1415926 / 180.0;
         dTempB = I * (1.0 - S);
         dTempR = I * (1.0 + (S * cos(H)) / cos(3.1415926 / 3.0 - H));
         dTempG = (3.0 * I - (dTempR + dTempB));
     }
     // GB扇区
     else if (H < 240.0 && H >= 120.0)
     {
         H -= 120.0;
         // 将H转为弧度表示
         H = H * 3.1415926 / 180.0;
         dTempR = I * (1.0 - S);
         dTempG = I * (1.0 + S * cos(H) / cos(3.1415926 / 3.0 - H));
         dTempB = (3.0 * I - (dTempR + dTempG));
     }
     // BR扇区
     else
     {
         H -= 240.0;
         // 将H转为弧度表示
         H = H * 3.1415926 / 180.0;
         dTempG = I * (1.0 - S);
         dTempB = I * (1.0 + (S * cos(H)) / cos(3.1415926 / 3.0 - H));
         dTempR = (3.0 * I - (dTempG + dTempB));
     }

     gl_FragColor = vec4(dTempR,dTempG, dTempB,1.0);

 }
    """.trimIndent()
}